package com.stylefeng.guns.modular.huamao.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.dao.UsersMapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.base.controller.BaseController;

import javax.naming.spi.DirStateFactory;
	
@RestController
@RequestMapping("/webAccount")
@CrossOrigin
public class WebAccountController extends BaseController {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private IUsersDrawsService usersDrawsService;
    @Autowired
    private IShoppingService shoppingService;
    @Autowired
    private IUsersUpgradeService usersUpgradeService;
    @Autowired
    private ISktSysConfigsService  sktSysConfigsService ;
    @Autowired
    private IAccountShopService  accountShopService;

    /**
     * 用户点击升级
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/getUseUpDate")
    public Result getUseUpDate(Integer userId) {
        JSONObject json = new JSONObject();
//		UsersDTO usersDTO =new UsersDTO();
//		usersDTO.setUserId(userId);
//		UsersDTO usersDT = usersService.selectOneUsersInfo(usersDTO);

        Users users = usersMapper.selectById(userId);
        if (users != null) {
            int userType = users.getUserType();
            if (userType == 0) {
                json.put("upAgentAccount", "997.00");
                json.put("upAgentScore", "99700.00");
                json.put("upManagerAccount", "9997.00");
                json.put("upManagerScore", "999700.00");
            } else if (userType == 1) {
                json.put("upManagerAccount", "9000.00");
                json.put("upManagerScore", "900000.00");
            }
            json.put("code", "01");
            json.put("msg", "成功");
        } else {
            json.put("code", "00");
            json.put("msg", "用户不存在");
        }
        return Result.OK(json);

    }

    /**
     * 用户升级点击确认支付
     * * @param userId   用户id
     *
     * @param userUpType 用户升级后角色
     * @return
     */
    @RequestMapping("/getCashToUp")
    public Result getCashToUp(Integer userId, Integer userUpType) {
        JSONObject json = accountService.getCashToUp(userId, userUpType);
        return Result.OK(json);
    }

    /**
     * 用户升级付款
     *
     * @param paypassword 支付密码
     * @return
     */
    @RequestMapping("/toUpPay")
    public Result toUpPay(UsersUpgrade usersUpgrade, String payPwd) {
        UsersUpgrade usersUpgrade1 = usersUpgradeService.selectById(usersUpgrade.getOrderId());
        usersUpgrade.setOrderNo(usersUpgrade1.getOrderNo());

        JSONObject json = accountService.updateByUp(usersUpgrade, payPwd);
        return Result.OK(json);
    }


    /**
     * 取消升级关于现金账户的变化
     *
     * @param usersUpgrade
     * @return
     */
    public JSONObject resetUPGrade(UsersUpgrade usersUpgrade) {
        JSONObject json = new JSONObject();
        boolean flag = accountService.resetUPGrade(usersUpgrade);
        if (flag == true) {
            json.put("code", "01");
            json.put("msg", "成功");
        } else {
            json.put("code", "00");
            json.put("msg", "失败");
        }
        return json;
    }


    /**
     * 获得用户现金账户余额
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getAccount")
    public Result getAccount(Integer userId) {
        JSONObject json = new JSONObject();

        Account account = accountService.selectAccountByuserId(userId);
        SktSysConfigs kaiyuanFe = sktSysConfigsService.selectSysConfigsByFieldCode("kaiyuanFee");//华宝支付费率
        String kaiyuanFee = kaiyuanFe.getFieldValue();
        SktSysConfigs taxRatios = sktSysConfigsService.selectSysConfigsByFieldCode("taxRatio"); //综合服务费
        String taxRatio = taxRatios.getFieldValue();
        SktSysConfigs kaiyuanturnFe = sktSysConfigsService.selectSysConfigsByFieldCode("kaiyuanturnFee"); //华宝货款支付费率
        String kaiyuanturnFee = kaiyuanturnFe.getFieldValue();
        AccountShop   userAccountShop=new AccountShop();
        userAccountShop.setUserId(userId);
        EntityWrapper<AccountShop> entityWrapper=new EntityWrapper<AccountShop>(userAccountShop) ;
        AccountShop userAccountShop1 = accountShopService.selectOne(entityWrapper);

        if (account != null) {
            json.put("code", "01");
            json.put("msg", "成功");
            json.put("cash", account.getCash());
            json.put("shoppingMoney", account.getShoppingMoney());
            json.put("kaiyuan", account.getKaiyuan());
            json.put("score", account.getScore());
            json.put("kaiyuanFee", kaiyuanFee);
            json.put("taxRatio", taxRatio);
            json.put("kaiyuanturnFee", kaiyuanturnFee);
            if(userAccountShop1!=null){
                BigDecimal kaiyuanturn=userAccountShop1.getKaiyuanTurnover();
                json.put("kaiyuanturn", kaiyuanturn);
            }else{
                json.put("kaiyuanturn", "0");
            }
        } else {
            json.put("code", "00");
            json.put("msg", "查询账户失败");
        }
        return Result.OK(json);

    }


    /**
     *   用户消费 输入支付密码提交
     * @param orderIdList  订单id集合
     * @param userId  用户id
     * @param payPwd 支付密码
     * @param payType  支付类型
     * @param payMoney  订单金额
     * @param feeMoney  费率（没有费率是传0）
     * @return
     */

    @RequestMapping("/sale")
	public  Result userSale(@RequestParam(value="orderIdList", required = false ) String orderIdList,
                            Integer userId,String payPwd,Integer payType,BigDecimal payMoney,BigDecimal feeMoney){
        String[] strings = orderIdList.split(",");
        List<String> lists=new ArrayList<>();
        for (int i=0;i<strings.length;i++){
            lists.add(strings[i]);
        }

        JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);
        if ("00".equals(jsonObject.get("code"))){
            return  Result.OK(jsonObject);
        }
        JSONObject json=new JSONObject();
        Map<String, Object> map = accountService.userSale(lists,payType,payMoney,feeMoney,userId);
        if("01".equals(map.get("code").toString())){
			json.put("code", "01");
			json.put("msg", "成功");
		}else{
			json.put("code", "00");
			json.put("msg", map.get("msg").toString());
		}
		return Result.OK(json);
	}

    //用户确认收货
    @RequestMapping("/toPayGoods")
    public Result toPayGoods(@RequestParam(value = "orderIdList", required = false) String orderIdList,Integer userId,String payPwd) {
        JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);
        if ("00".equals(jsonObject.get("code"))){
            return  Result.OK(jsonObject);
        }
        String[] strings = orderIdList.split(",");
        List<Integer> lists=new ArrayList<>();
        for (int i=0;i<strings.length;i++){
            lists.add(Integer.parseInt(strings[i]));
        }
        boolean flag = accountService.toPayGoods(lists);
        JSONObject json=new JSONObject();
        if (flag == true) {
            json.put("code", "01");
            json.put("msg", "成功");

        } else {
            json.put("code", "00");
            json.put("msg", "失败");
        }
        return Result.OK(json);
    }

    // 用户通过升级审核后
//    @RequestMapping("/upAfter")
//    public String upAfter(Integer userId, Boolean isManager, Users shareMan, Integer orderId,
//                          BigDecimal cash) {
//        // 给用户添加相应的积分,并且判断是否升级的是经理，直接分享人，用户添加积分类型为 用户升级 7,备注直接写死
//        accountService.upAfterAdd(userId, isManager, shareMan, orderId, cash.multiply(new BigDecimal("100")), 7,
//                "用户升级奖励");
//        return null;
//    }

    //用户确认退款

    /**
     * @param userId 用户id
     * @param cash   充值现金金额
     * @return
     */
    //用户充值生成订单
    @RequestMapping("/recharge")
    public Result recharge(Integer userId, BigDecimal totalMoney) {
    	BigDecimal amt= new BigDecimal("0"); 
    	if(totalMoney.compareTo(amt)==0 || totalMoney.compareTo(amt)<0){
    		return Result.EEROR("充值金额不能为0元");
    	}else{
            JSONObject json = accountService.recharge(userId, 4, totalMoney, "现金充值", 0);
            return Result.OK(json);
    	}

    }

    /**
     * 点击线下支付
     */
    @RequestMapping("/clickUnderLinePay")
    public Result clickUnderLinePay() {
        UnderLinePay underLinePay = accountService.clickUnderLinePay();
        return Result.OK(underLinePay);
    }

    /**
     * 订单id
     * Integer id,String remark,String orderImg
     *
     * @param recharge
     * @return
     */
    //线下支付提交
    @RequestMapping("/underLinePay")
    public Result underLinePay(UsersRecharge recharge) {
        Integer update = accountService.underLinePay(recharge);
        String message = "";
        if (update == 1) {
            message = "success";
            return Result.OK(null, message);
        } else {
            message = "error";
            return Result.EEROR(message);
        }

    }

    /**
     * @return
     */
    //充值成功后
    @RequestMapping("/rechargeAfter")
    public JSONObject rechargeAfter(UsersRecharge recharge) {
        JSONObject json = accountService.rechargeAfter(recharge);
        return json;
    }

    /**
     * 数据报表
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/getDateTable")
    public Result getDateTable(Integer userId) {
        BaseTable dataTable = accountService.getDataTable(userId);
        return Result.OK(dataTable);

    }


    //积分转化华宝
    public String scoreChange(Integer userId) {
        return null;
    }

    @GetMapping("/applyStockBefore")
    //申请库存积分
    public Result applyStockBefore() {
        //查询购买赠送比例
        String message = accountService.applyStockBefore();
        return Result.OK(null, message);
    }

    /**
     * 查询申请库存积分是否在购买时间段内
     *
     * @param shopId
     * @param cash   申请的现金
     * @return
     */
    @RequestMapping("/isBuyTime")
    public Result isBuyTime(Integer shopId, BigDecimal cash) {
        JSONObject json = accountService.isBuyTime(shopId, cash);
        String code = (String)json.get("code");
        if("00".equals(code)){
            String msg = (String)json.get("msg");
            return Result.EEROR(msg);
        }
        return Result.OK(json);
    }

    /**
     * @param userId     用户id
     * @param cash       金额
     * @param kaiyuanFee 开元宝服务费
     * @param payType    支付类型
     * @param score      购买库存积分数量
     * @return
     */
    //购买成功，添加库存扣除相应类型的金额
    @RequestMapping("/buyStockScoreAfter")
    public Result buyStockScoreAfter(SktOrdersStockscore sktOrdersStockscore, String payPwd) {
        JSONObject jsonObject = accountService.buyStockScoreAfter(sktOrdersStockscore, payPwd);
        Object code = jsonObject.get("code");
        if("00".equals(code.toString())){
            Object msg = jsonObject.get("msg");
            return Result.EEROR(msg.toString());
        }
        return Result.OK(jsonObject);
    }

    @RequestMapping("/doUpAgent")
    public void doUpAgent() {
        String s = accountService.doUpAgent(1, 1);
        System.out.println(s);
    }

//    //股东分红
//    public Result shareBonus(Integer agentId) {
//        accountService.shareBonus(agentId);
//        return null;
//    }

    /**
     * 回显用户数据
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getAccountByUserId")
    public Result getAccountByUserId(Integer userId) {
        //JSONObject json=new JSONObject();
        AccountList accountList = accountService.getAccountByUserId(userId);
        return Result.OK(accountList);

    }

    /**
     * 线下发送积分
     *
     * @param userId
     * @param shopId
     * @param score
     * @return
     */


    @RequestMapping("/sendScore")
    //JSONObject json=new JSONObject();
    public Result sendScore(Integer userId, Integer shopId, BigDecimal score, String payPwd, BigDecimal totalMoney, Integer scoreRatio, String orderRemarks) {


        JSONObject json = accountService.sendScore(userId, shopId, score, payPwd, totalMoney, scoreRatio, orderRemarks);
        return Result.OK(json);
    }

    /**
     * 查询我的优惠券
     * @param status  优惠券状态
     * @param userId  用户id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @RequestMapping("/myShopping")
    public Result myShopping(String status,Integer userId,String startTime,String endTime){
        Users user=   usersService.selectById(userId);
        if (user!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("dataId",user.getUserId());
            map.put("status",status);
            map.put("dataFlag",1);
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            List<Map<String, Object>> maps = shoppingService.selectShoppingList(map);
            return    Result.OK(maps);
        }else {
            return   Result.EEROR("无用户信息");
        }
    }


    /**
     *   用户消费 输入支付密码提交
     * @param orderIdList  订单id集合
     * @param userId  用户id
     * @param payPwd 支付密码
     * @param payType  支付类型
     * @param payMoney  订单金额
    * @param payKaiyuan  支付华宝或者华宝货款
     * @param feeKaiyuan 支付华宝或者华宝货款手续费
     * param  payShopping  支付优惠券
     * @return
     */

    @RequestMapping("/payment")
    public  Result payment(@RequestParam(value="orderIdList", required = false ) String orderIdList,
                            Integer userId,String payPwd,Integer payType,BigDecimal payMoney,BigDecimal payKaiyuan,
                           BigDecimal payKaiyuanFee,BigDecimal payShopping,String thirdNo,Integer thirdType,String payName){
        String[] strings = orderIdList.split(",");
        List<String> lists=new ArrayList<>();
        for (int i=0;i<strings.length;i++){
            lists.add(strings[i]);
        }

//        JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);
//        if ("00".equals(jsonObject.get("code"))){
//            return  Result.OK(jsonObject);
//        }
        JSONObject json=new JSONObject();
        Map<String, Object> map = accountService.payment( lists,userId,payType,
                payMoney,payKaiyuan, payKaiyuanFee,payShopping,thirdNo,thirdType,  payName);
        if("01".equals(map.get("code").toString())){
            json.put("code", "01");
            json.put("msg", "成功");
        }else{
            json.put("code", "00");
            json.put("msg", map.get("msg").toString());
        }
        return Result.OK(json);
    }



    /**
     *  //用户确认收货(现金+华宝 或者现金+华宝货款)
     * @param orderIdList 订单id集合
     * @param userId  用户id
     * @param payPwd 密码
     * @return
     */

    @RequestMapping("/enter")
    public Result enter(@RequestParam(value = "orderIdList", required = false) String orderIdList,Integer userId,String payPwd) {
        JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);
        if ("00".equals(jsonObject.get("code"))){
            return  Result.OK(jsonObject);
        }
        String[] strings = orderIdList.split(",");
        List<Integer> lists=new ArrayList<>();
        for (int i=0;i<strings.length;i++){
            lists.add(Integer.parseInt(strings[i]));
        }
        boolean flag = accountService.enter(lists);
        JSONObject json=new JSONObject();
        if (flag == true) {
            json.put("code", "01");
            json.put("msg", "成功");

        } else {
            json.put("code", "00");
            json.put("msg", "失败");
        }
        return Result.OK(json);
    }
    @RequestMapping("/checkShopping")
    public Result checkShopping(String userId, BigDecimal shoppingMoney){
        Map<String, Object> map = accountService.checkShopping(userId, shoppingMoney);
        if ("00".equals(map.get("code").toString())){
          return   Result.EEROR(map.get("msg").toString());
        }else {
            return Result.OK(map);
        }

    }
}
